package com.cskaoyan.config;

import com.cskaoyan.convert.String2DateConverter;
import org.hibernate.validator.HibernateValidator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


// @ComponentScan("com.cskaoyan.controller")
@EnableWebMvc
@Configuration
public class MvcConfiguration implements WebMvcConfigurer {

    @Value("${pic.storage-location}")
    private String picStorePath;

    @Value("${pic.mapping-url}")
    private String picMappingUrl;


    // 请求参数校验
    @Override
    public Validator getValidator() {
        LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
        localValidatorFactoryBean.setProviderClass(HibernateValidator.class);
        return localValidatorFactoryBean;
    }

    // 日期和字符串的转换
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new String2DateConverter());
    }


    // 文件上传组件注册
    @Bean
    public CommonsMultipartResolver multipartResolver() {  // 方法名必须为这个，不能更改；因为id为固定值，而方法名就是id
        return new CommonsMultipartResolver();
    }

    // 文件的mapping和location映射
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(picMappingUrl).addResourceLocations("file:"+picStorePath);
        // registry.addResourceHandler("/storage/fetch/**").addResourceLocations("file:e:/a/");
        // registry.addResourceHandler("storage/fetch/**").addResourceLocations("file:e:/a/");
        // registry.addResourceHandler("**").addResourceLocations("file:e:/a/");
    }



}
